/*
 * Copyright:  2018 smarabbit studio.
 *
 *  Licensed under the Confluent Community License; you may not use this file
 *  except in compliance with the License.  You may obtain a copy of the License at
 *
 *  http://www.confluent.io/confluent-community-license
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OF ANY KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations under the License.
 *
 *  @作   者： 黄开晖 (117227773@qq.com)
 *  @日   期:  2020年11月3日
 */
package com.massyframework.beanskin.launching.web;

import java.util.Collections;
import java.util.EventListener;
import java.util.List;
import java.util.function.Consumer;

import javax.servlet.ServletContextListener;

import com.massyframework.beanskin.assembly.AssemblyContext;
import com.massyframework.beanskin.assembly.AssemblyContextSupport;
import com.massyframework.beanskin.service.ServiceRepository;

/**
 * @author huangkh
 *
 */
public abstract class ServletContextListenerTracker extends AssemblyContextSupport {
	
	private List<ServletContextListener> listeners;

	/**
	 * 
	 */
	public ServletContextListenerTracker() {
		this.listeners = Collections.emptyList();
	}

	
	/**
	 * 迭代执行
	 * @param <T>
	 * @param listenerType {@link Class}
	 * @param action {@link Consumer}, 消费者
	 */
	protected <T extends EventListener> void foreachListener(Class<T> listenerType, Consumer<T> action) {
		for (ServletContextListener listener: this.listeners) {
			if (listenerType.isAssignableFrom(listener.getClass())){
				T obj = listenerType.cast(listener);
				action.accept(obj);
			}
		}
	}
	
	

	@Override
	protected void bindAssemblyContext(AssemblyContext context) {
		super.bindAssemblyContext(context);
		ServiceRepository repo = ServiceRepository.retrieveFrom(context.getAssociatedAssembly());
		this.listeners = repo.getServices(ServletContextListener.class);
	}


	@Override
	protected void unbindAssemblyContext(AssemblyContext context) {
		this.listeners = Collections.emptyList();
		super.unbindAssemblyContext(context);
	}

}
